//
//  LCAppDelegate+LCAVPlay.m
//  LCMusicPlayer
//
//  Created by jiukuyinyue on 2017/9/29.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCAppDelegate+LCAVPlay.h"
//#import "NSObject+MemoryLeak.h"

@implementation LCAppDelegate (LCAVPlay)

- (void)setupAVAudioConfig {
    //[NSObject addClassNamesToWhitelist:@[@"LCAccLoginViewController"]];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[LCFloatingWindow sharedInstance] show:nil didCloseBlock:nil];
        [LCHistoryDataManager loadBibleTextData];
    });

//    //设置静音也播放 后台播放
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [session setActive:YES error:nil];
    
    //call phone后 继续播放
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(onAudioSessionEvent:)
                                                 name: AVAudioSessionInterruptionNotification
                                               object: [AVAudioSession sharedInstance]];
    
    //添加通知，拔出耳机后暂停播放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];
    
    [self becomeFirstResponder];
    //远程的控制相关
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
}
/**
 *  一旦输出改变则执行此方法
 *
 *  @param notification 输出改变通知对象
 */
-(void)routeChange:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo;
    int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];
    //等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
    if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];
        //原设备为耳机则暂停
        if ([portDescription.portType isEqualToString:@"Headphones"]) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [_LCPlayer pause];
            }];
            
        }
    }
    
}

-(BOOL)becomeFirstResponder{
    return YES;
}
//call phone后 继续播放
-(void)onAudioSessionEvent:(NSNotification *)notification {
    AVAudioSessionInterruptionType typeValue = [notification.userInfo[AVAudioSessionInterruptionTypeKey] integerValue];
    if (typeValue == AVAudioSessionInterruptionTypeBegan) {
        [_LCPlayer pause];
    }else if (typeValue == AVAudioSessionInterruptionTypeEnded){
//        [_LCPlayer play];
        NSLog(@"typeValue == AVAudioSessionInterruptionTypeEnded");
    }
    
}


@end
